package com.qf.service.impl;

import com.qf.constans.ResultCode;
import com.qf.dto.Md5;
import com.qf.dto.UsersDto;
import com.qf.exceptions.QuaryDataException;
import com.qf.mapper.UsersMapper;
import com.qf.pojo.Users;
import com.qf.service.IUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;

@Service
public class UsersServiceImpl implements IUsersService {

    private UsersMapper usersMapper;
    @Autowired
    public void setUsersMapper(UsersMapper usersMapper) {
        this.usersMapper = usersMapper;
    }

    @Override
    public int addUser(UsersDto users) {

        String salt = Md5.RandomSalt();
        String salfpassword = Md5.Md5AndSalt(salt, users.getPassword());
        System.out.println("加盐了"+salt);
        users.setPassword(salfpassword);
        users.setPasswordsalt(salt);

        int i = usersMapper.addUser(users);
        return i;
    }


    public Users login(Users users){
        Users user = usersMapper.findByUsername(users.getUsername());
        if(user==null){
            throw new QuaryDataException("用户不存在", ResultCode.NULL_DATA);
        }
        String password = users.getPassword();
        System.out.println("用户密码"+password);

        String passwordsalt = user.getPasswordsalt();

        String salfpassword = Md5.Md5AndSalt(passwordsalt,password);
        System.out.println("用户密码加盐"+salfpassword);
        System.out.println("数据库加盐密码"+user.getPassword());

        if(!salfpassword.equals(user.getPassword())){
            throw new QuaryDataException("密码不正确", ResultCode.NULL_DATA);
        }
        return user;
    }

}
